package com.fivec.javaproject.net;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.Set;

/**
 * @author wangyizhu
 * @version "1.8.0_131"
 * @email 2641956765@qq.com
 * @desc:该类用于封装提供网络请求的功能代码，用于发起网络请求，并将响应的数据返回
 * @Time 2021/12/06 10:38
 */
public class HttpUtils {
    /*
     * 该函数用于实现get请求，并将请求结果进行返回
     * @param path 请求的资源路径
     * @return 请求的结果
     * */
    public static String get(String path) {
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        String line = "";//最开始空行
        String result = "";//每次读取到累计起来的读取结果
        try {
            //Union Resource Location  统一资源定位
            URL url = new URL((path));
            URLConnection connection = url.openConnection();
            //进行连接
            connection.connect();
            inputStream = connection.getInputStream();
            //字符流:按行读
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader((inputStreamReader));

            while ((line = reader.readLine()) != null) {
                result += line;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭读取流
            try {
                if (reader != null) {
                    reader.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 封装的用java实现的原生post请求
     *
     * @param path   请求的路径
     * @param header 请求头设置信息
     * @param data   请求数据
     * @return 请求的结果
     */

    public static String post(String path, Map<String, String> header, byte[] data) {
        OutputStream outputStream = null;
        String result = "";//result表示最后要返回的数据
        BufferedReader reader = null;
        //io:
        // 输入流：字节输入流，字符读取流
        // 输出流：字节输出流，字符写入流
        // 字节字符转换流
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置可以发送数据和接收数据
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");//设置请求类型
            //设置请求头属性
            //ContentType:application/json
            //Authorization:"Basic"+base64(用户信息)
            if (!header.isEmpty()) {//header不为空
                //将header中的数据遍历，设置到请求头当中
                //遍历map
                Set<String> keys = header.keySet();
                //如何遍历set？ foreach,迭代器
                for (String key : keys
                ) {
                    String value = header.get(key);
                    conn.setRequestProperty(key, value);
                }
            }
            conn.connect();
            //把请求数据发送到请求的服务端
            outputStream = conn.getOutputStream();
            outputStream.write(data);
            outputStream.flush();

            //等待接收返回的数据
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                result += line;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return result;
    }

}
